package com.authine.cloudpivot.web.api.secondopen.utils;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpRestUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpRestUtil.class);

    private static RestTemplate restTemplate;

    static {
        restTemplate = new RestTemplate();
    }

    /**
     * post请求(无加密)，json参数
     *
     * @param url
     * @param valueJson
     * @return
     */
    public static String httpPostUrlWithoutEncrypt(String url, String valueJson) {
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("multipart/form-data"));
//        headers.add("Accept", "*/*");
        HttpEntity<String> entity = new HttpEntity<>(valueJson, headers);
        String jsonResposeStr = null;
        try {
            ResponseEntity<String> respose = restTemplate.postForEntity(url, entity, String.class);
            jsonResposeStr = respose.getBody();
        } catch (Exception e) {
            logger.info("请求异常 返回null 错误信息{}", e);
        }
        return jsonResposeStr;
    }


    /**
     * post请求，增加token参数
     *
     * @param url
     * @param valueJson
     * @return
     */
    public static String httpPostUrlWithoutEncryptInLogin(String url, String valueJson,String token) {
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
        headers.add("Accept", "*/*");
        headers.add("access_token",token);
        HttpEntity<String> entity = new HttpEntity<>(valueJson, headers);
        String jsonResposeStr = null;
        try {
            ResponseEntity<String> respose = restTemplate.postForEntity(url, entity, String.class);
            jsonResposeStr = respose.getBody();
        } catch (Exception e) {
            logger.info("请求异常 返回null 错误信息{}", e);
        }
        return jsonResposeStr;
    }


    /**
     * get请求
     *
     * @param url
     * @return
     */
    public static String httpGetUrlWithoutEncrypt(String url,String corp,String domain,String code,String token) {
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
        headers.add("x-corp", corp);
        headers.add("x-domain", domain);
        headers.add("x-code", code);
        headers.add("x-token", token);
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(null, headers);
        String jsonResposeStr = null;
        try {
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
            jsonResposeStr = response.getBody();
        } catch (Exception e) {
            logger.info("请求异常 返回null 错误信息{}", e);
        }
        return jsonResposeStr;
    }


    /**
     * get请求(无加密)
     *
     * @param url
     * @return
     */
    public static String httpGetUrlWithoutEncrypt(String url) {
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        headers.add("Accept", "application/json; charset=UTF-8");
//        headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
//        headers.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(null, headers);
        String jsonResposeStr = null;
        try {
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
            jsonResposeStr = response.getBody();
            jsonResposeStr=new String(jsonResposeStr.getBytes("iso-8859-1"),"utf-8");
        } catch (Exception e) {
            logger.info("请求异常 返回null 错误信息{}", e);
        }
        return jsonResposeStr;
    }


    /**
     * post请求，qad请求，增加header四个参数
     *
     * @param url
     * @param valueJson
     * @return
     */
    public static String httpPostUrlWithoutEncryptInLogin(String url,String corp,String domain,String code,String token,String valueJson) {
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
        headers.add("x-corp", corp);
        headers.add("x-domain", domain);
        headers.add("x-code", code);
        headers.add("x-token", token);
        HttpEntity<String> entity = new HttpEntity<>(valueJson, headers);
        String jsonResposeStr = null;
        try {
            ResponseEntity<String> respose = restTemplate.postForEntity(url, entity, String.class);
            jsonResposeStr = respose.getBody();
        } catch (Exception e) {
            logger.info("请求异常 返回null 错误信息{}", e);
        }
        return jsonResposeStr;
    }


    /**
     * post请求，map参数
     * @param url
     * @param valueMap
     * @return
     */
    public static String httpPostUrl(String url,  MultiValueMap<String, String> valueMap){
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(valueMap,headers);
        String jsonResposeStr=null;
        try{
            ResponseEntity<String> respose = restTemplate.postForEntity(url, entity, String.class);
            jsonResposeStr=respose.getBody();
        }catch (Exception e){
            logger.info("请求异常 返回null 错误信息{}",e);
        }
        return jsonResposeStr;
    }
    public static String httpPostUrlEam(String url, String param) {
        String resp = restTemplate.postForEntity(url, JSONObject.parseObject(param), String.class).getBody();
        return resp;
    }


    public static String postDataSOAP(String _url, String _data) {
        String msg = "";
        try {
            URL url = new URL(_url);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setAllowUserInteraction(false);
            con.setUseCaches(false);
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
            con.addRequestProperty("Content-Type", "text/xml;charset=UTF-8");
            con.setRequestProperty("contentType", "UTF-8");
            con.setRequestProperty("Accept-Charset", "UTF-8");
            con.setRequestProperty("SOAPAction", "execute");


            OutputStream outputStream = con.getOutputStream();
            outputStream.write(_data.getBytes("UTF-8"));
            outputStream.close();
            InputStream inputStream = con.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();


            inputStream.close();
            inputStream = null;
            con.disconnect();
            msg = buffer.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return msg;
    }
}
